<template>
  <div class="text-descriptor">
    <el-card class="descriptor-card">
      <template #header>
        <div class="card-header">
          <span>Descriptor</span>
          <div class="header-actions">
            <el-button type="info" size="small" @click="copyDescriptors" :loading="isCopying">
              <el-icon><DocumentCopy /></el-icon>
              复制
            </el-button>
            <el-button type="success" size="small" @click="importDescriptors" :loading="isImporting">
              <el-icon><FolderOpened /></el-icon>
              导入
            </el-button>
            <el-button type="warning" size="small" @click="exportDescriptors" :loading="isExporting">
              <el-icon><Download /></el-icon>
              导出
            </el-button>
            <el-button type="primary" size="small" @click="applyToFields" :loading="isApplying">
              <el-icon><Upload /></el-icon>
              应用
            </el-button>
          </div>
        </div>
      </template>
      <div ref="descriptorEditorContainer" class="descriptor-editor-container"></div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, watch } from 'vue'
import { Upload, DocumentCopy, Download, FolderOpened } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { invoke } from '@tauri-apps/api/core'

interface FieldData {
  id: string
  label: string
  display_name: string
  hidden: boolean
  x_descriptors: string[]
  x_descriptor_count: number
  children_descriptor_count: number
  children?: FieldData[]
  description?: string
}

const props = defineProps<{
  treeData: FieldData[]
  shouldSync?: number
}>()

const emit = defineEmits<{
  (e: 'descriptors-change', descriptors: any[]): void
  (e: 'update-fields', updatedTreeData: FieldData[]): void
}>()

const descriptorEditorContainer = ref<HTMLElement | null>(null)
let monaco: any = null
let descriptorEditor: any = null

const defaultDescriptorText = `specDescriptors: []`

// 复制和导出状态
const isCopying = ref(false)
const isExporting = ref(false)
const isImporting = ref(false)
const isApplying = ref(false) // 添加应用状态标志

// 使用Rust后端转换树数据为YAML格式

// 从字段数据同步到编辑器
const syncFromFields = async () => {
  if (!descriptorEditor || !props.treeData || props.treeData.length === 0) return
  
  try {
    const yamlContent = await invoke('tree_to_yaml_descriptors', { 
      treeData: props.treeData 
    }) as string
    
    descriptorEditor.setValue(yamlContent)
  } catch (error) {
    console.error('同步失败:', error)
    ElMessage.error(`同步失败: ${error}`)
  }
}

// 解析 YAML 并应用到字段
const applyToFields = async () => {
  if (!descriptorEditor) return
  
  try {
    isApplying.value = true // 设置应用状态
    const content = descriptorEditor.getValue()
    console.log('要应用的YAML内容:', content)
    
    // 使用Rust后端解析YAML
    const parsedDescriptors = await invoke('parse_yaml_descriptors', { 
      yamlContent: content 
    }) as any[]
    console.log('解析后的描述符:', parsedDescriptors)
    
    // 使用Rust后端应用到树数据
    const updatedTreeData = await invoke('apply_descriptors_to_tree', {
      treeData: props.treeData,
      descriptors: parsedDescriptors
    }) as FieldData[]
    console.log('应用后的树数据:', updatedTreeData)
    
    // 发送更新后的树数据
    emit('update-fields', updatedTreeData)
  } catch (error) {
    ElMessage.error('解析或应用描述符配置失败，请检查格式')
    console.error('Apply error:', error)
  } finally {
    isApplying.value = false // 重置应用状态
  }
}

// 监听树数据变化，自动同步
watch(() => props.treeData, async (newData, oldData) => {
  if (!descriptorEditor || isApplying.value) return // 如果正在应用，不要同步
  
  // 在初始化时或者数据变化时自动同步
  if (!oldData || newData.length === 0) {
    try {
      console.log('Initial sync or empty data, triggering sync...', newData)
      await syncFromFields()
    } catch (error) {
      console.error('监听数据变化时发生错误:', error)
    }
  }
}, { deep: true, immediate: true })

// 监听shouldSync变化，当收到同步指令时执行同步
watch(() => props.shouldSync, async (newValue) => {
  if (!descriptorEditor || isApplying.value || !newValue) return
  
  try {
    console.log('Manual sync triggered, syncing from fields...')
    await syncFromFields()
  } catch (error) {
    console.error('手动同步时发生错误:', error)
  }
})

// 复制描述符到剪贴板
const copyDescriptors = async () => {
  if (!descriptorEditor) {
    ElMessage.warning('编辑器未初始化')
    return
  }
  
  try {
    isCopying.value = true
    
    const content = descriptorEditor.getValue()
    
    if (!content.trim()) {
      ElMessage.warning('没有可复制的内容')
      return
    }
    
    // 复制到剪贴板
    await navigator.clipboard.writeText(content)
    
    ElMessage.success('已复制到剪贴板')
  } catch (error) {
    console.error('复制失败:', error)
    ElMessage.error('复制失败，请检查浏览器权限')
  } finally {
    isCopying.value = false
  }
}

// 导入描述符文件
const importDescriptors = async () => {
  try {
    isImporting.value = true
    
    // 使用Tauri的文件打开对话框
    const content = await invoke('open_file_dialog') as string
    
    if (!content || content.trim() === '') {
      ElMessage.warning('文件内容为空或读取失败')
      return
    }
    
    // 验证YAML格式
    try {
      await invoke('validate_yaml', { yamlText: content })
    } catch (error) {
      ElMessage.error('文件格式不正确，请选择有效的YAML文件')
      return
    }
    
    // 设置编辑器内容
    if (descriptorEditor) {
      descriptorEditor.setValue(content)
    }
  } catch (error) {
    if (error === 'Dialog cancelled') {
      ElMessage.info('已取消导入')
    } else {
      console.error('导入失败:', error)
      ElMessage.error('导入失败: ' + error)
    }
  } finally {
    isImporting.value = false
  }
}

// 导出描述符为文件
const exportDescriptors = async () => {
  if (!descriptorEditor) {
    ElMessage.warning('编辑器未初始化')
    return
  }
  
  try {
    isExporting.value = true
    
    const content = descriptorEditor.getValue()
    
    if (!content.trim()) {
      ElMessage.warning('没有可导出的内容')
      return
    }
    
    // 使用Tauri的文件保存对话框
    const result = await invoke('save_file_dialog', {
      content: content,
      defaultFileName: `descriptors-${new Date().toISOString().slice(0, 10)}.yaml`
    }) as string
    
    if (result === 'cancelled') {
      ElMessage.info('已取消导出')
    } else {
      ElMessage.success('文件已保存')
    }
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败: ' + error)
  } finally {
    isExporting.value = false
  }
}

onMounted(async () => {
  await initEditor()
})

async function initEditor() {
  if (!descriptorEditorContainer.value) return
  if (!monaco) {
    monaco = (await import('monaco-editor'))
  }
  descriptorEditor = monaco.editor.create(descriptorEditorContainer.value, {
    value: defaultDescriptorText,
    language: 'yaml',
    theme: 'vs-dark',
    automaticLayout: true,
    minimap: { enabled: true },
    readOnly: false
  })
}

onBeforeUnmount(() => {
  if (descriptorEditor) {
    descriptorEditor.dispose()
  }
})
</script>

<style lang="scss" scoped>
.text-descriptor {
  height: 100%;
  
  .descriptor-card {
    height: 100%;
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .header-actions {
        display: flex;
        gap: 8px;
      }
    }
    
    .descriptor-editor-container {
      height: calc(50vh - 120px);
      min-height: 200px;
    }
  }
}
</style> 